//
//  AnalyticsLogger.m
//  Pennyworth
//
//  Created by Chris Karr on 12/5/08.
//  Copyright 2008 Northwestern University. All rights reserved.
//

#import "AnalyticsLogger.h"
#import "Learner.h"
#import "Observation.h"
#import "AppleScriptPrediction.h"

@implementation AnalyticsLogger

/*
 * To enable from Terminal.app:
 *
 * defaults write net.aetherial.context.Pennyworth "Enable Analytics" -bool YES
 *
 */

- (void) awakeFromNib
{
	predictions = [[NSMutableDictionary dictionary] retain];
	
	if ([[NSUserDefaults standardUserDefaults] valueForKey:ENABLE_ANALYTICS] != nil)
	{
		NSLog (@"Analytics enabled");
		
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processEvent:) name:ANALYTIC_EVENT object:nil];
		stateTimer = [[NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(saveState:) userInfo:nil repeats:YES] retain];
		
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processPrediction:) name:PREDICTION_FETCHED object:nil];

		NSDictionary * postObject = [NSDictionary dictionaryWithObjectsAndKeys:@"Launched Application", ANALYTIC_NAME, @"", ANALYTIC_VALUE, nil];
		[[NSNotificationCenter defaultCenter] postNotificationName:ANALYTIC_EVENT object:postObject];

		[stateTimer fire];
	}
}

- (void) processEvent:(NSNotification *) theNote
{
	NSDictionary * event = [theNote object];
	
	NSLog (@"Analytic Event: %@", [event valueForKey:ANALYTIC_NAME]);
	
	NSObject * value = [event valueForKey:ANALYTIC_VALUE];
	
	if ([value isKindOfClass:[NSDictionary class]])
	{
		NSDictionary * dict = (NSDictionary *) value;
		
		NSArray * keys = [[dict allKeys] sortedArrayUsingSelector:@selector(compare:)];
		
		for (NSString * key in keys)
			NSLog (@"%@: %@", key, [dict valueForKey:key]);
	}
	else
		NSLog (@"Event Value: %@", value);
}

- (void) saveState:(NSTimer *) theTimer
{
	NSMutableDictionary * state = [NSMutableDictionary dictionary];
	
	for (Observation * obs in [observations arrangedObjects])
		[state setValue:obs.observation forKey:obs.sensor];

	NSDictionary * postObject = [NSDictionary dictionaryWithObjectsAndKeys:@"State Update", ANALYTIC_NAME, state, ANALYTIC_VALUE, nil];
	
	[[NSNotificationCenter defaultCenter] postNotificationName:ANALYTIC_EVENT object:postObject];
}

- (void) processPrediction:(NSNotification *) note
{
	NSDictionary * userInfo = [note userInfo];
	
	NSString * key = [userInfo valueForKey:KEY];
	NSObject * value = [userInfo valueForKey:PREDICTION];
	
	if (key == nil || value == nil)
		return;
	
	if (![[predictions valueForKey:key] isEqual:value])
	{
		NSDictionary * postObject = [NSDictionary dictionaryWithObjectsAndKeys:key, ANALYTIC_NAME, value, ANALYTIC_VALUE, nil];
		[[NSNotificationCenter defaultCenter] postNotificationName:ANALYTIC_EVENT object:postObject];
		
		[predictions setValue:value forKey:key];
	}
}

@end
